package edu.cornell.cs4740.wsd;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class Dictionary {

	private Map<Word, DictionaryEntry> dictionaryMap;

	public Dictionary(String dictionaryPath) throws ParserConfigurationException, SAXException, IOException {
		dictionaryMap = new HashMap<Word, DictionaryEntry>();
		File dictionaryFile = new File(dictionaryPath);

		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		DocumentBuilder builder = dbf.newDocumentBuilder();
		Document dictXml = builder.parse(dictionaryFile);

		NodeList allEntries = dictXml.getElementsByTagName("lexelt");

		for (int x = 0; x < allEntries.getLength(); x++) {
			Element wordElement = (Element) allEntries.item(x);
			String wordPos = wordElement.getAttribute("item");

			Word word = null;
			try {
				word = new Word(wordPos);
			} catch (Exception e) {
				System.err.println("Failed to parse " + wordPos);
				e.printStackTrace();
			}

			DictionaryEntry de = new DictionaryEntry(word);

			NodeList senseList = wordElement.getElementsByTagName("sense");

			for (int j = 0; j < senseList.getLength(); j++) {
				Element sense = (Element) senseList.item(j);
				String definition = sense.getAttribute("gloss");
				de.addSense(new Integer(j), definition);
			}
			
			dictionaryMap.put(word, de);
		}

	}

}
